package com.zscg.sequence.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zgcs.sequence.net.in.CurrentSequencePackage;
import com.zgcs.sequence.net.in.GameTimeoutPackage;
import com.zgcs.sequence.net.in.IdiomGamePackage;
import com.zgcs.sequence.net.in.InPackage;
import com.zgcs.sequence.net.in.JoinRoomPackage;
import com.zgcs.sequence.net.in.RoomCommentPackage;
import com.zgcs.sequence.net.in.StartGamePackage;
import com.zgcs.sequence.tool.ServiceTool;
import com.zscg.sequence.R;
import com.zscg.sequence.data.Room;
import com.zscg.sequence.data.User;
import com.zscg.sequence.model.UserManager;
import com.zscg.sequence.service.SequenceService;

public class GamingActivity extends SequenceActivity implements OnClickListener {

	public static final int START_GAME = 1;
	public static final int START_GAME_FAIL = 2;
	public static final int MESSAGE_COUNT_DOWN = 1;
	public static final int MESSAGE_SEQUENCE_FAIL = 2;

	public static final int DIALOG_WAITTING = 1;
	public static final int DIALOG_REQUENCE_FAIL = 2;
	public static final int DIALOG_REQUENCE_SUCESS = 3;
	public static final int DIALOG_REQUENCE_READY = 4;

	ListView gamingList;
	GamingListAdapter listAdapter;
	ArrayList<HashMap<String, Object>> dataList;
	Room room;
	int ownerID;
	String ownerName;
	Dialog countdownDialog;
	Dialog waittingDialog;
	TextView countDownText;
	LinearLayout inputLinear;
	LinearLayout cheerButtonLinear;
	EditText input;
	Button sendButton, laughButton, comeonButton, greateButton, quickButton;
	TextView tips;

	CountDownTimer countDownTimer, dialogTimer;

	Handler myHandler;

	int currentCount = 30;

	String currentStartKey;
	User currentUser;
	String currentFirst;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gaming);
		dataList = new ArrayList<HashMap<String, Object>>();
		room = (Room) getIntent().getSerializableExtra("room");
		ownerID = getIntent().getIntExtra("ownerID", 0);
		ownerName = getIntent().getStringExtra("ownerName");
		currentStartKey = room.keywords;
		// showDialog(START_GAME);
		if (room.state == JoinRoomPackage.STATE_ROOM_GAMING) {
			showWaittingDialog(DIALOG_REQUENCE_READY);
		} else {
			showWaittingDialog(DIALOG_WAITTING);
		}

		// for (int i = 0; i < 11; i++) {
		// HashMap<String, Object> map = new HashMap<String, Object>();
		// map.put("name", "你猜" + i);
		// map.put("icon", BitmapFactory.decodeResource(getResources(),
		// R.drawable.avatar_default_large));
		// map.put("first", "龙" + i);
		// map.put("second", "行" + i);
		// map.put("third", "天" + i);
		// map.put("forth", "下" + i);
		// dataList.add(map);
		// }

		gamingList = (ListView) findViewById(R.id.gaming_list);
		listAdapter = new GamingListAdapter(this);
		gamingList.setAdapter(listAdapter);

		inputLinear = (LinearLayout) findViewById(R.id.input_view);
		input = (EditText) inputLinear.findViewById(R.id.sequenceinput);
		sendButton = (Button) inputLinear.findViewById(R.id.send);
		sendButton.setOnClickListener(this);

		cheerButtonLinear = (LinearLayout) findViewById(R.id.cheer_buttons);
		laughButton = (Button) cheerButtonLinear
				.findViewById(R.id.laugh_button);
		comeonButton = (Button) cheerButtonLinear
				.findViewById(R.id.comeon_button);
		greateButton = (Button) cheerButtonLinear
				.findViewById(R.id.great_button);
		quickButton = (Button) cheerButtonLinear
				.findViewById(R.id.quick_button);
		laughButton.setOnClickListener(this);
		comeonButton.setOnClickListener(this);
		greateButton.setOnClickListener(this);
		quickButton.setOnClickListener(this);
		tips = (TextView) findViewById(R.id.tip);
		countDownText = (TextView) findViewById(R.id.countdown_text);

		if (ownerID == UserManager.getInstance().getUser().getUserId()) {
			showCountDown();
		} else {
			showCheer();
		}
		SequenceService.clinet.getCurrentSequenceUser(room.roomId);
		addSequence(ownerName, room.keywords, null, null, null, null);

	}

	private void addSequence(String name, String first, String second,
			String third, String forth, String icon) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		map.put("icon", BitmapFactory.decodeResource(getResources(),
				R.drawable.avatar_default_large));
		map.put("first", first);
		map.put("second", second);
		map.put("third", third);
		map.put("forth", forth);
		dataList.add(map);
		listAdapter.notifyDataSetChanged();
	}

	@Override
	protected void addselfFilter() {
		intentFilter.addAction(ServiceTool.ORDER_RIG);
		intentFilter.addAction(ServiceTool.ORDER_RGA);
		intentFilter.addAction(ServiceTool.ORDER_GT);
		intentFilter.addAction(ServiceTool.ORDER_RIC);
		intentFilter.addAction(ServiceTool.ORDER_RICU);
	}

	@Override
	protected void disposeSelf(Context context, Intent intent) {
		String action = intent.getAction();

		if (ServiceTool.ORDER_RISG.equals(action)) {
			StartGamePackage startGame = (StartGamePackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RISG);

			int result = startGame.getResult();
			if (result == InPackage.RESULT_SUCESS) {
				if (UserManager.getInstance().getUser().getUserId() == startGame
						.getOwnerID()) {
					// 自己是房主，进入倒计时输入状态
					showCountDown();
				} else {
					// 自己不是房主，不用处理

					// if(room.desc)

				}
			} else {
				showDialog(START_GAME_FAIL);
			}

		} else if (ServiceTool.ORDER_RIG.equals(action)) {

			IdiomGamePackage idiomGame = (IdiomGamePackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RIG);
			if (idiomGame.getRoomID() == room.roomId) {
				currentFirst = idiomGame.getAnswerKey();
				if (idiomGame.getResult() == InPackage.RESULT_SUCESS) {
					if (idiomGame.getCurrentUserID() == UserManager
							.getInstance().getUser().getUserId()) {
						// 自己回答结果
						showWaittingDialog(DIALOG_REQUENCE_SUCESS);
					}
					String first = idiomGame.getAnswerKey().substring(0, 1);
					String second = idiomGame.getAnswerKey().substring(0, 1);
					String third = idiomGame.getAnswerKey().substring(0, 1);
					String forth = idiomGame.getAnswerKey().substring(0, 1);
					addSequence(idiomGame.getNextUserNickname(), first, second,
							third, forth, null);
					addSequence(idiomGame.getNextUserNickname(), first, second,
							third, forth, null);
				} else {
					if (idiomGame.getCurrentUserID() == UserManager
							.getInstance().getUser().getUserId()) {
						// 自己回答结果
						showWaittingDialog(DIALOG_REQUENCE_FAIL);
					}
					dataList.remove(dataList.size() - 1);
					String first = idiomGame.getAnswerKey().substring(0, 1);
					String second = idiomGame.getAnswerKey().substring(0, 1);
					String third = idiomGame.getAnswerKey().substring(0, 1);
					String forth = idiomGame.getAnswerKey().substring(0, 1);
					addSequence(idiomGame.getNextUserNickname(), first, second,
							third, forth, null);

				}
				if (idiomGame.getNextUserID() == UserManager.getInstance()
						.getUser().getUserId()) {
					showCountDown();
				}

			}

		} else if (ServiceTool.ORDER_RIC.equals(action)) {
			RoomCommentPackage roomComment = (RoomCommentPackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RIC);
			showRoomComment(roomComment.getUserNic(),
					roomComment.getToUserNic(), roomComment.getCommentStyle());

		} else if (ServiceTool.ORDER_GT.equals(action)) {
			GameTimeoutPackage timeout = (GameTimeoutPackage) intent
					.getSerializableExtra(ServiceTool.ORDER_GT);
			if (room.roomId == timeout.getRoomID()) {
				dataList.remove(dataList.size() - 1);
				User user = new User();
				user.setUserId(timeout.getNextID());
				user.setUserNickName(timeout.getNextNickName());
				currentUser = user;
				addSequence(user.getUserNickName(), currentFirst, null, null,
						null, null);
			}

		} else if (ServiceTool.ORDER_RICU.equals(action)) {
			CurrentSequencePackage currentSe = (CurrentSequencePackage) intent
					.getSerializableExtra(ServiceTool.ORDER_RICU);
			if (room.roomId == currentSe.getRoomID()) {
				currentUser = currentSe.getUser();
			}
		}

	}

	@Override
	protected void disposeLogin(Intent intent) {
		// TODO Auto-generated method stub

	}

	class GamingListAdapter extends BaseAdapter {
		LayoutInflater mInflater;

		public GamingListAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return dataList.size() / 5 + 1;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				// LayoutInflater vi =
				// (LayoutInflater)GamingActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				// convertView = vi.inflate(R.layout.gaming_list_item, parent,
				// false);
				convertView = mInflater
						.inflate(R.layout.gaming_list_item, null);
				// LinearLayout.inflate(GamingActivity.this,
				// R.layout.gaming_list_item, parent , false);
				holder = new ViewHolder();
				holder.firstHead = (LinearLayout) convertView
						.findViewById(R.id.first_head);
				// holder.firstHead = firstHead;
				// holder.firstHeadImg = (ImageView) firstHead
				// .findViewById(R.id.head_icon);
				// holder.firstName = (TextView) firstHead
				// .findViewById(R.id.head_name);
				holder.first_idiom_first = (TextView) convertView
						.findViewById(R.id.first_idiom_first_text);

				// if ((dataList.size() % 5) > 1) {
				holder.secondView = (LinearLayout) convertView
						.findViewById(R.id.second_view);
				// holder.first_idiom_second = (TextView) secondView
				// .findViewById(R.id.second_text);
				// holder.first_idiom_third = (TextView) secondView
				// .findViewById(R.id.third_text);
				// holder.first_idiom_forth = (TextView) secondView
				// .findViewById(R.id.fourth_text);

				holder.secondHead = (LinearLayout) convertView
						.findViewById(R.id.second_head);
				// holder.secondHeadImg = (ImageView) secondHead
				// .findViewById(R.id.head_icon);
				// holder.secondName = (TextView) secondHead
				// .findViewById(R.id.head_name);

				// }

				// if (dataList.size() % 5 > 2) {
				holder.thirdView = (LinearLayout) convertView
						.findViewById(R.id.third_view);
				// holder.second_idiom_second = (TextView) thirdView
				// .findViewById(R.id.second_text);
				// holder.second_idiom_third = (TextView) thirdView
				// .findViewById(R.id.third_text);
				// holder.second_idiom_forth = (TextView) thirdView
				// .findViewById(R.id.fourth_text);

				holder.thirdHead = (LinearLayout) convertView
						.findViewById(R.id.third_head);
				// holder.thirdHeadImg = (ImageView) thirdHead
				// .findViewById(R.id.head_icon);
				// holder.thirdName = (TextView) thirdHead
				// .findViewById(R.id.head_name);
				// }
				// if (dataList.size() % 5 > 3) {
				holder.fourthView = (LinearLayout) convertView
						.findViewById(R.id.fourth_view);
				// holder.third_idiom_second = (TextView) fourthView
				// .findViewById(R.id.second_text);
				// holder.third_idiom_third = (TextView) fourthView
				// .findViewById(R.id.third_text);
				// holder.third_idiom_forth = (TextView) fourthView
				// .findViewById(R.id.fourth_text);

				holder.fourthHead = (LinearLayout) convertView
						.findViewById(R.id.fourth_head);
				// holder.thirdHeadImg = (ImageView) thirdHead
				// .findViewById(R.id.head_icon);
				// holder.thirdName = (TextView) thirdHead
				// .findViewById(R.id.head_name);
				// }
				// if (dataList.size() % 5 > 4) {
				holder.fifthView = (LinearLayout) convertView
						.findViewById(R.id.fifth_view);
				// holder.third_idiom_second = (TextView) fourthView
				// .findViewById(R.id.second_text);
				// holder.third_idiom_third = (TextView) fourthView
				// .findViewById(R.id.third_text);
				// }

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			((ImageView) holder.firstHead.findViewById(R.id.head_icon))
					.setImageBitmap((Bitmap) dataList.get(position * 5).get(
							"icon"));
			((TextView) holder.firstHead.findViewById(R.id.head_name))
					.setText("" + dataList.get(position * 5).get("name"));
			holder.first_idiom_first.setText(""
					+ dataList.get(position * 5).get("first"));

			if (((dataList.size() - position * 5) > 5)
					|| (dataList.size() % 5) > 1 || dataList.size() % 5 == 0) {
				holder.secondView.setVisibility(View.VISIBLE);
				((TextView) holder.secondView.findViewById(R.id.second_text))
						.setText(""
								+ dataList.get(position * 5 + 1).get("second"));
				((TextView) holder.secondView.findViewById(R.id.third_text))
						.setText(""
								+ dataList.get(position * 5 + 1).get("third"));
				((TextView) holder.secondView.findViewById(R.id.fourth_text))
						.setText(""
								+ dataList.get(position * 5 + 1).get("fourth"));

				holder.secondHead.setVisibility(View.VISIBLE);
				((ImageView) holder.secondHead.findViewById(R.id.head_icon))
						.setImageBitmap((Bitmap) dataList.get(position * 5 + 1)
								.get("icon"));
				((TextView) holder.secondHead.findViewById(R.id.head_name))
						.setText(""
								+ dataList.get(position * 5 + 1).get("name"));
			} else {
				holder.secondView.setVisibility(View.GONE);
				holder.secondHead.setVisibility(View.GONE);
			}

			if (((dataList.size() - position * 5) > 5)
					|| dataList.size() % 5 > 2 || dataList.size() % 5 == 0) {
				holder.thirdView.setVisibility(View.VISIBLE);
				((TextView) holder.thirdView.findViewById(R.id.second_text))
						.setText(""
								+ dataList.get(position * 5 + 2).get("second"));
				((TextView) holder.thirdView.findViewById(R.id.third_text))
						.setText(""
								+ dataList.get(position * 5 + 2).get("third"));
				((TextView) holder.thirdView.findViewById(R.id.fourth_text))
						.setText(""
								+ dataList.get(position * 5 + 2).get("fourth"));

				holder.thirdHead.setVisibility(View.VISIBLE);
				((ImageView) holder.thirdHead.findViewById(R.id.head_icon))
						.setImageBitmap((Bitmap) dataList.get(position * 5 + 2)
								.get("icon"));
				((TextView) holder.thirdHead.findViewById(R.id.head_name))
						.setText(""
								+ dataList.get(position * 5 + 2).get("name"));
			} else {
				holder.thirdView.setVisibility(View.GONE);
				holder.thirdHead.setVisibility(View.GONE);
			}

			if (((dataList.size() - position * 5) > 5)
					|| dataList.size() % 5 > 3 || dataList.size() % 5 == 0) {
				holder.fourthView.setVisibility(View.VISIBLE);
				((TextView) holder.fourthView.findViewById(R.id.second_text))
						.setText(""
								+ dataList.get(position * 5 + 3).get("second"));
				((TextView) holder.fourthView.findViewById(R.id.third_text))
						.setText(""
								+ dataList.get(position * 5 + 3).get("third"));
				((TextView) holder.fourthView.findViewById(R.id.fourth_text))
						.setText(""
								+ dataList.get(position * 5 + 3).get("fourth"));

				holder.fourthHead.setVisibility(View.VISIBLE);
				((ImageView) holder.fourthHead.findViewById(R.id.head_icon))
						.setImageBitmap((Bitmap) dataList.get(position * 5 + 3)
								.get("icon"));
				((TextView) holder.fourthHead.findViewById(R.id.head_name))
						.setText(""
								+ dataList.get(position * 5 + 3).get("name"));
			} else {
				holder.fourthView.setVisibility(View.GONE);
				holder.fourthHead.setVisibility(View.GONE);
			}

			if (((dataList.size() - position * 5) > 5)
					|| dataList.size() % 5 > 4 || dataList.size() % 5 == 0) {
				holder.fifthView.setVisibility(View.VISIBLE);
				((TextView) holder.fourthView.findViewById(R.id.second_text))
						.setText(""
								+ dataList.get(position * 5 + 3).get("second"));
				((TextView) holder.fourthView.findViewById(R.id.third_text))
						.setText(""
								+ dataList.get(position * 5 + 3).get("third"));
			} else {
				holder.fifthView.setVisibility(View.GONE);
			}

			return convertView;
		}

		class ViewHolder {

			ImageView firstHeadImg, secondHeadImg, thirdHeadImg, forthHeadImg;
			TextView firstName, secondName, thirdName, forthName;
			TextView first_idiom_first, first_idiom_second, first_idiom_third,
					first_idiom_forth;
			TextView second_idiom_second, second_idiom_third,
					second_idiom_forth;
			TextView third_idiom_second, third_idiom_third, third_idiom_forth;
			TextView forth_idiom_second, forth_idiom_third, forth_idiom_forth;

			LinearLayout firstHead, secondHead, thirdHead, fourthHead;
			LinearLayout firstView, secondView, thirdView, fourthView,
					fifthView;

		}

	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		String msg = null;
		switch (id) {
		case START_GAME:
			msg = "正在开始游戏……";
			break;
		}
		dialog = ProgressDialog.show(this, "提示", msg);
		return dialog;
	}

	private void showWaittingDialog(int type) {

		waittingDialog = new Dialog(this);
		waittingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		waittingDialog.setContentView(R.layout.gaming_waitting_dialog);
		waittingDialog.findViewById(R.id.gaming_waitting_sure)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogTimer.cancel();
						waittingDialog.dismiss();
					}
				});
		String msg = null;

		switch (type) {
		case DIALOG_WAITTING:
			msg = "本轮已结束，请等待下一轮开始！";
			break;
		case DIALOG_REQUENCE_FAIL:
			msg = "接龙失败，下轮再接再厉！";
			break;
		case DIALOG_REQUENCE_SUCESS:
			msg = "接龙成功，获得5枚龙蛋！";
			break;
		case DIALOG_REQUENCE_READY:
			msg = "您有20秒时间接龙";
			break;
		}
		((TextView) waittingDialog.findViewById(R.id.content)).setText(msg);
		waittingDialog.show();
		if (dialogTimer == null) {
			dialogTimer = new CountDownTimer(3000, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onFinish() {
					if (waittingDialog != null && waittingDialog.isShowing())
						waittingDialog.dismiss();

				}
			};
		}
		dialogTimer.start();

	}

	private void showCountDown() {
		inputLinear.setVisibility(View.VISIBLE);
		countDownText.setVisibility(View.VISIBLE);
		currentCount = 30;

		if (myHandler == null)
			myHandler = new MyHanlder();

		if (countDownTimer == null) {
			countDownTimer = new CountDownTimer(30000, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					if (currentCount > 0)
						currentCount--;
					myHandler.sendEmptyMessage(MESSAGE_COUNT_DOWN);

				}

				@Override
				public void onFinish() {
					currentCount = 0;
					myHandler.sendEmptyMessage(MESSAGE_SEQUENCE_FAIL);
					SequenceService.clinet.gameTimeout(UserManager
							.getInstance().getUser().getUserId());
				}
			};
		}
		countDownTimer.start();
	}

	private void sequenceResule(int result) {
		inputLinear.setVisibility(View.GONE);
		countDownText.setVisibility(View.GONE);
		countDownTimer.cancel();
		cheerButtonLinear.setVisibility(View.VISIBLE);
		if (result == 1) {
			// 成功
		} else {
			// 失败
		}

	}

	class MyHanlder extends Handler {
		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_COUNT_DOWN:
				countDownText.setText("" + currentCount);
				break;
			case MESSAGE_SEQUENCE_FAIL:
				sequenceResule(0);
				break;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			String text = input.getText().toString();
			if (text != null && text.length() >= 4) {

				if (text.startsWith(currentStartKey)) {
					SequenceService.clinet.idiomGame(room.roomId,
							currentStartKey, text);
				} else {
					Toast.makeText(this, "亲，不符合接龙规则哦！", Toast.LENGTH_LONG)
							.show();
				}

			} else {
				Toast.makeText(this, "输入不能为空", Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.laugh_button:
			SequenceService.clinet.roomComment(room.roomId,
					currentUser.getUserId(),
					RoomCommentPackage.ROOM_COMMENT_LAUGH);
			break;
		case R.id.comeon_button:
			SequenceService.clinet.roomComment(room.roomId,
					currentUser.getUserId(),
					RoomCommentPackage.ROOM_COMMENT_COMEON);

			break;
		case R.id.great_button:
			SequenceService.clinet.roomComment(room.roomId,
					currentUser.getUserId(),
					RoomCommentPackage.ROOM_COMMENT_GREAT);

			break;
		case R.id.quick_button:
			SequenceService.clinet.roomComment(room.roomId,
					currentUser.getUserId(),
					RoomCommentPackage.ROOM_COMMENT_QUICK);

			break;
		}
	}

	private void showCheer() {
		cheerButtonLinear.setVisibility(View.VISIBLE);
	}

	private void showRoomComment(String userNic, String toUserNic,
			int commentStyle) {

		String msg = null;
		switch (commentStyle) {
		case RoomCommentPackage.ROOM_COMMENT_LAUGH:
			msg = "你真糗！練這個都不懂";
			break;
		case RoomCommentPackage.ROOM_COMMENT_COMEON:
			msg = "加油，加油！";
			break;
		case RoomCommentPackage.ROOM_COMMENT_GREAT:
			msg = "你好棒哦！";
			break;
		case RoomCommentPackage.ROOM_COMMENT_QUICK:
			msg = "快点呗，等的花儿都谢了！";
			break;
		}
		tips.setText(userNic + "对" + toUserNic + "说：" + msg);
	}

}
